package com.icinfo.cloud.provider.common.utils;

import com.icinfo.framework.mybatis.mapper.util.StringUtil;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import gui.ava.html.image.generator.HtmlImageGenerator;
import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.util.IOUtils;

import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：pdf转图片工具类
 *
 * @author shishengyao
 * @description
 * @date 2022/8/11
 */
public class PdfUtil {
    /**
     * dpi越大转换后越清晰，相对转换速度越慢
     */
    private static final Integer DPI = 100;

    /**
     * 转换后的图片类型
     */
    private static final String IMG_TYPE = "png";

    /**
     * 描述：pdf转图片（仅支持一页，多页会有文件丢失）
     *
     * @param pdfUrl pdf格式的url
     * @author shishengyao
     * @date 2022/08/17
     */
    public static String pdfTransImage(String pdfUrl) {
        if (StringUtil.isEmpty(pdfUrl)) {
            return "";
        }
        String imageBase64Str = "";
        try {
            URL url = new URL(pdfUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_TYPE, outputStream);
                byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());
                outputStream.flush();
                outputStream.close();
                imageBase64Str = new String(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:image/png;base64," + imageBase64Str;
    }

    /**
     * pdf转图片支持多页
     *
     * @param pdfUrl
     * @return {@link List< String>}
     * @author liyafeng
     * @date 2023/7/6
     */
    public static List<String> pdfTransMultipleImage(String pdfUrl) {
        List<String> imgBase64List = new ArrayList<>();
        if (StringUtil.isEmpty(pdfUrl)) {
            return imgBase64List;
        }
        String imageBase64Str = "";
        try {
            URL url = new URL(pdfUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_TYPE, outputStream);
                byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());
                outputStream.flush();
                outputStream.close();
                imageBase64Str = new String(bytes);
                imgBase64List.add("data:image/png;base64," + imageBase64Str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return "data:image/png;base64," + imageBase64Str;
        return imgBase64List;
    }


    /**
     * 描述：pdf转灰色图片（仅支持一页，多页会有文件丢失）
     *
     * @param pdfUrl pdf格式的url
     * @author shishengyao
     * @date 2022/08/17
     */
    public static String pdfTransGrayImage(String pdfUrl) {
        if (StringUtil.isEmpty(pdfUrl)) {
            return "";
        }
        String imageBase64Str = "";
        try {
            URL url = new URL(pdfUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                image = getGrayPicture(image);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_TYPE, outputStream);
                byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());
                outputStream.flush();
                outputStream.close();
                imageBase64Str = new String(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:image/png;base64," + imageBase64Str;
    }

    public static void main(String[] args) {
//        String base64 = pdfTransImage("https://csoss-test.oss-cn-shanghai.aliyuncs.com/xfjdzf/2023/0706/8ae43bef5c8743a1b925f7ebcf162500.pdf");
//        System.out.println(base64);

        getPdfByte("https://csoss-test.oss-cn-shanghai.aliyuncs.com/xfjdzf/2023/0725/e57a17109a3a4e8d9856c317eae5a4f4.png");

    }

    public static String getImage(String htmlstr) {
        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        imageGenerator.loadHtml(htmlstr);
        BufferedImage bufferedImage = getGrayPicture(imageGenerator.getBufferedImage());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", outputStream);
            String base64Img = Base64.encodeBase64String(outputStream.toByteArray());
            String res = "data:image/jpg;base64," + base64Img.toString();
            return res;

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public static BufferedImage getGrayPicture(BufferedImage originalImage) {
        BufferedImage grayPicture;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();

        grayPicture = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp cco = new ColorConvertOp(ColorSpace
                .getInstance(ColorSpace.CS_GRAY), null);
        cco.filter(originalImage, grayPicture);
        return grayPicture;
    }

    /**
     * 描述：合并PDF文档
     *
     * @param fileUrlList 文件的url列表
     * @return {@link byte[] }
     * @author shishengyao
     * @date 2022/12/08
     */
    public static byte[] mergePdfFiles(List<String> fileUrlList) {
        byte[] desFileBuffer = null;
        String outputFile = BaseUtil.createUid() + ".pdf";
        File parentFile = new File("pdfFiles");
        try {

            // 合并PDF文档
            File outFile = new File(parentFile, outputFile);
            if (!outFile.exists()) {
                outFile.mkdir();
            }
            PDFMergerUtility merger = new PDFMergerUtility();
            for (String e : fileUrlList) {
                try {
                    URL url = new URL(e);
                    URLConnection connection = url.openConnection();
                    InputStream inputStream = connection.getInputStream();
                    merger.addSource(inputStream);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            merger.setDestinationFileName(outFile.getName());
            // 合并PDF
            merger.mergeDocuments(null);
            FileInputStream fis = new FileInputStream(outputFile);
            desFileBuffer = FileUtil.InputStreamToByte(fis);
            fis.close();
            outFile.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return desFileBuffer;
    }


    /**
     * 合并pdf文件带页码
     *
     * @param fileUrlList 文件的url列表
     * @param startPage   页码开始页面
     * @return {@link byte[] }
     * @author shishengyao
     * @date 2022/12/13
     */
    public static byte[] mergePdfFilesWithPageNumber(List<String> fileUrlList, int startPage) {
        byte[] desFileBuffer = null;
        FileInputStream fis = null;
        String dir = "pdfFiles";
        String dirFilePath = dir + File.separator + "mergePdf";
        String outputFilePath = dirFilePath + File.separator + BaseUtil.createUid() + ".pdf";
        File fileMkd = new File(dirFilePath);
        File outputFile = new File(outputFilePath);
        try {
            //pdf临时生成目录
            if (!fileMkd.exists()) {
                fileMkd.mkdirs();
            }

            outputFile.createNewFile();

            PDFMergerUtility merger = new PDFMergerUtility();
            for (String e : fileUrlList) {
                URL url = new URL(e);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = connection.getInputStream();
                merger.addSource(inputStream);
            }
            merger.setDestinationFileName(outputFilePath);
            // 合并PDF
            merger.mergeDocuments(null);
            fis = new FileInputStream(outputFilePath);
            addPageNum(fis, outputFilePath, startPage);
            fis = new FileInputStream(outputFilePath);
            desFileBuffer = FileUtil.InputStreamToByte(fis);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputFile.delete();
            fileMkd.delete();
        }
        return desFileBuffer;
    }

    /**
     * 生成文件pdf
     *
     * @param url
     * @return
     */
    public static byte[] getPdfByte(String url) {
        byte[] desFileBuffer = null;
        FileInputStream fis = null;
        String dir = "pdfFiles";
        String dirFilePath = dir + File.separator + "mergePdf";
        String outputFilePath = dirFilePath + File.separator + BaseUtil.createUid() + ".pdf";
        File fileMkd = new File(dirFilePath);
        File outputFile = new File(outputFilePath);
        //pdf临时生成目录
        if (!fileMkd.exists()) {
            fileMkd.mkdirs();
        }
        try {
            outputFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        PdfWriter pdfWriter = null;
        try {
            pdfWriter = new PdfWriter(outputFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);
        document.add(new Paragraph(url));
        document.close();
        try {
            fis = new FileInputStream(outputFilePath);
        } catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
        try {
            desFileBuffer = FileUtil.InputStreamToByte(fis);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            outputFile.delete();
        }
        return desFileBuffer;
    }

    public static Document imageToPdf(String oosUrl) {
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) new URL(oosUrl).openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        urlConnection.setReadTimeout(5000);
        urlConnection.setConnectTimeout(5000);
        try {
            urlConnection.setRequestMethod("GET");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        InputStream inputStream = null;
        try {
            inputStream = urlConnection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = new byte[0];
        try {
            bytes = IOUtils.toByteArray(inputStream, 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Image image = null;
        try {
            image = new Image(ImageDataFactory.create("C:\\Users\\hzhb\\Desktop\\ecbd69d9041ca40db16bde75ea649d7.jpg"));
//            image = new Image(ImageDataFactory.create(bytes));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        image.setAutoScale(true);
        File file = new File("C:\\Users\\hzhb\\Desktop\\2222.pdf");
        PdfWriter pdfWriter = null;
        try {
            pdfWriter = new PdfWriter(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);
//        String path = "C:\\Windows\\Fonts\\simsun.ttc,0";//windows里的字体资源路径
//        try {
//            PdfFont font = PdfFontFactory.createFont(path, PdfEncodings.IDENTITY_H, false);
//            document.setFont(font);
////            BaseFont.CreateFont("C:\\Windows\\Fonts\\simsun.ttc,0", PdfEncodings.IDENTITY_H,false)；
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        document.add(new Paragraph(oosUrl));
//        document.add(image);
        document.close();
        return document;
    }

    public static Integer getPercent(float h, float w) {
        Integer g = 0;
        Float g2 = 0.0f;
        g2 = 480 / w * 100;
        g = Math.round(g2);
        return g;
    }


    /**
     * 描述：pdf添加页码
     *
     * @param srcIns      资源
     * @param outFilePath 输入文件路径
     * @param startPage   开始页
     * @author shishengyao
     * @date 2022/12/13
     */
    public static void addPageNum(FileInputStream srcIns, String outFilePath, int startPage) {
        try {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(srcIns), new PdfWriter(outFilePath));
            Document doc = new Document(pdfDoc);
            int numberOfPages = pdfDoc.getNumberOfPages();
            for (int i = 1; i <= numberOfPages; i++) {
                // Write aligned text to the specified by parameters point
                if (i > startPage) {
                    doc.showTextAligned(new Paragraph(String.format("%s", i - startPage)),
                            295, 26, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0);
                }
            }
            doc.close();
            srcIns.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
